<template>
  <div class="section">
    <h2 class="section-title">{{ title }}</h2>
    <div v-if="loading" class="loading-container">
      <LottieAnimation animation-link="https://lottie.host/5f3a8bde-4e6a-4f7e-8c9b-2b7e6b4e8b1e/3j4Y4Yj3dZ.json" :width="400" :height="400" />
    </div>
    <div v-else class="app-grid" :id="gridId">
      <masonry-wall :items="apps" :ssr-columns="1" :column-width="320" :gap="24">
        <template #default="{ item }">
          <div class="app-card-wrapper">
            <AppCard
              :app="item"
              :featured="featured"
              @view-chat="(appId) => $emit('view-chat', appId)"
              @view-work="(app) => $emit('view-work', app)"
            />
          </div>
        </template>
      </masonry-wall>
    </div>
    <div class="pagination-wrapper">
      <a-pagination
        v-model:current="page.current"
        v-model:page-size="page.pageSize"
        :total="page.total"
        :show-size-changer="false"
        :show-total="(total: number) => `共 ${total} 个${featured ? '案例' : '应用'}`"
        @change="loadApps"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import AppCard from '@/components/AppCard.vue'
import LottieAnimation from '@/components/LottieAnimation.vue'
import MasonryWall from '@yeger/vue-masonry-wall'
import { getDeployUrl } from '@/config/env'

const props = defineProps<{
  title: string
  apps: API.AppVO[]
  loading: boolean
  page: {
    current: number
    pageSize: number
    total: number
  }
  gridId: string
  featured?: boolean
  loadApps: () => void
}>()

const { title, apps, loading, page, gridId, featured, loadApps } = toRefs(props)

const router = useRouter()

const viewChat = (appId: string | number | undefined) => {
  if (appId) {
    router.push(`/app/chat/${appId}?view=1`)
  }
}

const viewWork = (app: API.AppVO) => {
  if (app.deployKey) {
    const url = getDeployUrl(app.deployKey)
    window.open(url, '_blank')
  }
}
</script>

<style scoped>
.section {
  margin-bottom: 60px;
}

.section-title {
  font-size: 32px;
  font-weight: 600;
  margin-bottom: 32px;
  color: #1e293b;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.app-grid {
  display: block;
  margin-bottom: 32px;
}

.app-card-wrapper {
  transform-style: preserve-3d;
  perspective: 1000px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}
</style>